package HTTP

import (
	"SQL/FSDB"
	"SQL/db"
	"SQL/myDB"
	"SQL/util"
	"logs"
	"net/http"
	"time"
)

//const addr = "120.25.208.100:8001"

const addr = ":8001"

type router struct {
}

// Router 路由，按照名字分隔个人负责的接口
func Router() {

	//--------------------------------------------------dy
	err := myDB.OpenSql()
	if err != nil {
		logs.Print(err)
		panic(err)
	}

	//--------------------------------------------------Ficow Shen
	err = FSDB.Open()
	if err != nil {
		logs.Print(err.Error())
		panic(err)
	}

	//--------------------------------------------------Pismery
	util.InitDb()

	//--------------------------------------------------Decaf
	err = db.Opendb()
	if err != nil {
		logs.Print(err.Error())
		panic(err)
	}

	resetDB("resetDB")
	go dispatchMessages()
	r := &router{}
	http.ListenAndServe(addr, r)
}

func (r router) ServeHTTP(w http.ResponseWriter, req *http.Request) {

	config(w, req)
	switch req.URL.Path {
	//--------------------------------------------------dy
	case "/deleteGroupMember":
		deleteGroupMember(w, req)
	case "/addGroupMember":
		addGroupMember(w, req)
	case "/addGroup":
		addGroup(w, req)
	case "/confirmAddGroupMember":
		confirmAddGroupMember(w, req)
	case "/setData":
		setData(w, req)
	case "/dbPage":
		dbPage(w, req)
	//--------------------------------------------------Ficow Shen
	case "/ws":
		initWebSocket(w, req)
	case "/login":
		login(w, req)
	case "/chatMessageList":
		chatMessageList(w, req)
	case "/sessionListWithFriend":
		sessionListWithFriend(w, req)
	case "/sessionListWithGroup":
		sessionListWithGroup(w, req)
	//--------------------------------------------------Pismery
	case "/getObjectData":
		getObjectData(w, req)
	case "/sendMessage":
		sendMessage(w, req)
	case "/alterObjectData":
		alterObjectData(w, req)
	case "/deleteGroup":
		deleteGroup(w, req)
	//--------------------------------------------------Decaf
	case "/addUser":
		addUser(w, req)
	case "/getFriendList":
		getFriendList(w, req)
	case "/getGroupList":
		getGroupList(w, req)
	case "/getGroupMember":
		getGroupMember(w, req)
	case "/uploadIcon":
		upload(w, req)
	case "/getIcon":
		getIcon(w, req)
	//--------------------------------------------------
	default:
		http.NotFound(w, req)
	}
}
func config(w http.ResponseWriter, req *http.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "*")                    //允许访问所有域
	w.Header().Add("Access-Control-Allow-Headers", "Content-Type,Origin") //header的类型
	w.Header().Add("Content-Type", "application/json; charset=utf-8")     //返回数据格式是json

	req.ParseForm()
	printRequestInfo(req)
}
func printRequestInfo(req *http.Request) {
	//logs.PrintParent(fmt.Println(time.Now(), req.RemoteAddr, req.Method, req.URL.Path))
	logs.Print(time.Now(), req.RemoteAddr, req.Method, req.URL.Path)
}
